<?php
/**
 * Created by PhpStorm.
 * User: DR
 * Date: 2018/8/3
 * Time: 18:55
 */

namespace app\api\model;


use think\Db;
use think\exception\ValidateException;

class UserMill extends BaseModel
{
    protected $hidden = ['user_id', 'mill_id', 'earnings_yet', 'period', 'last_time','delete_time'];

    //购买矿机
    public static function buyMill($user, $mill_id)
    {
        Db::startTrans();
        try{
            $mill = self::userCanBuy($user, $mill_id);          //检测当前用户是否可以购买矿机
            $userMill = [
                'user_id' => $user->id,
                'mill_id' => $mill_id,
                'earnings' => $mill->earnings,
                'earnings_yet' => 0,
                'sac' => 0,
                'period' => 0,
                'status' => 0,
                'price' => $mill->price,
                'buy_time' => time(),
                'total_days' => $mill->period
            ];
            self::insert($userMill);
            Db::name('burn')->where(['parent_id'=>$user->id])->setInc('burn',$mill->price);
            $user->is_buymill = 1;                              //买矿机后用户表更新字段
            $user->save();
            parent::dealUserMoney($user, $mill->price * -1);
            account_log($user->id, $mill->price * -1, $user->cny+$user->freeze_cny, '', $user->sac+$user->freeze_sac, '购买' . $mill->mill_name);
            platform_log($user->id, $mill->price, '用户购买矿机');
            self::buyMillDivide($user, $mill->price);
            Db::commit();
        }catch (\Exception $e) {
            throw $e;
            // 回滚事务
            Db::rollback();
        }
    }

    //启动矿机
    public static function startMyMill($id, $user_id)
    {
        $usermill = self::with('mill')->find($id);
        $period = $usermill->mill->period;
        if ($usermill->status != '0') {
            throw new ValidateException('当前矿机已启用或已到期!');
        }
        if ($usermill->user_id != $user_id) {
            throw new ValidateException('当前矿机不属于该用户');
        }
        $usermill->status = 1;
        $usermill->start_time = time();
        $usermill->end_time = time() + $period * 24 * 3600;
        $usermill->save();
    }

    //购买矿机和利润上级分成
    /*
     * @param int $money 矿机单价
     * @param string $currency 币种
     */
    public static function buyMillDivide($user, $money)
    {
        if ($user->first)               //一级分成
        {
            self::millDivide($user, $user->first, 'first', $money);
        }
        if ($user->second)              //二级分成
        {
            self::millDivide($user, $user->second, 'second', $money);
        }
        if ($user->third)                //三级分成
        {
            self::millDivide($user, $user->third, 'third', $money);
        }
    }

    //购买和利润分成
    public static function millDivide($user, $superior, $type, $money)
    {
        $superior = User::get(['id' => $superior]);
        $money = self::isBurn($user, $superior, $money);  //是否开启烧伤制度
        $is_bought = self::isBought($superior, $type);     //下级是否拥有矿机和拥有的人数
        if ($is_bought) {
            self::startBuyDivide($superior,$money,$type,$user);
        }
    }

    //开始购买分成
    public static function startBuyDivide($superior,$money,$type,$user)
    {
        if( $money ==  0 ){
            return ;
        }
        $proportion = config('site.'. $type .'_lease_reward') * 0.01;
        $reward = $proportion * $money;
        $superior->cny = $superior->cny + $reward;
        $superior->total_cny = $superior->total_cny + $reward;
        $superior->save();
        $desc = 'ID:'. $user->id . ',手机号:' . $user->mobile .'购买矿机的分成';
        account_log($superior->id,$reward,$superior->cny,'',$user->sac,$desc,'','','','2');
        platform_log($superior->id,$reward * -1,$desc);
    }


    //是否需要下级买过矿机并且满足人数要求
    public static function isBought($superior, $type)
    {
        $user_recommend = new UserRecommend();
        $recommend = $user_recommend->where('user_id', $superior->id)
            ->find();
        $user = new User();
        $where = [
            'id' => ['in', $recommend['son_id']],
            'status' => 'normal',
            'is_buymill' => config('site.is_bought'),
        ];
        $count = $user->where($where)
            ->count();
        if ($count < config('site.' . $type . '_lease_neednum')) {
            return false;
        }
        return true;
    }

    //是否开启烧伤
    /*
     * $user  object 当前用户
     * $superior  object  上级用户
     * $mill  object  矿机
     */
    public static function isBurn($user, $superior, $money)
    {
        if (config('site.is_burn')) {
            $burnModel = new Burn();
            $burn = $burnModel->where(['user_id'=>$user->id,'parent_id'=>$superior->id])->find();
            if($burn){
                if($burn->burn > $money)
                {
                    $burn->burn -= $money;
                }else{
                    $money = $burn->burn;
                    $burn->burn = 0;
                }
                $burn->save();
                return $money;
            }else{
                $sum = self::where('user_id','=',$superior->id)->sum('price');
                if($sum > $money)
                {
                    $sum -= $money;
                }else{
                    $money = $sum;
                    $sum = 0;
                }
                $data = [
                    'user_id' => $user->id,
                    'parent_id' => $superior->id,
                    'burn' => $sum,
                ];
                $burnModel->data($data)->save();
                return $money;
            }
        }
        return $money;
    }

    //检查当前用户是否可以买矿机
    public static function userCanBuy($user, $mill_id)
    {
        $where = [
            'user_id' => $user->id,
            'mill_id' => $mill_id,
            'status' => ['in', '0,1'],
        ];
        $num = self::where($where)->count();
        $mill = Mill::get(['id' => $mill_id]);
        if ($num >= $mill->num) {
            throw new ValidateException('超出可购买数量');
        }
        parent::checkUserCny($user, $mill->price);
        return $mill;
    }

    public function mill()
    {
        return $this->belongsTo('mill', 'mill_id', 'id');
    }

    public function getBuyTimeAttr($value, $data)
    {
        return $this->getDateTime($value, $data);
    }

    public function getStartTimeAttr($value, $data)
    {
        return $this->getDateTime($value, $data);
    }

    public function getEndTimeAttr($value, $data)
    {
        return $this->getDateTime($value, $data);
    }

//    public function getStatusAttr($value)
//    {
//        $status = [0 => '未启用', 1 => '运行中', 2 => '已到期'];
//        return $status[$value];
//    }
}
